import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';
import router from 'umi/router';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Button,
  Card,
  Row,
  Col,
  Input,
  Timeline,
  message,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

import { ModelType } from './model';

const { TextArea } = Input;
const { Item } = Form;
interface saveAndEditProps extends FormComponentProps {
  dispatch: Dispatch;
  detailInfo: any;
  courierCompanySaveAndEdit: ModelType;
  location: { query: any };
}

interface saveAndEditState {
  formValues: object;
}

@connect(({ propertyCompanySaveAndEdit: { detailInfo } }: any) => ({ detailInfo }))

class saveAndEditInfo extends Component<saveAndEditProps, saveAndEditState> {
  state: saveAndEditState = {
    formValues: {},
  };

  componentDidMount() {
    const {
      location: { query: { id } },
    } = this.props;
    if (id) this.fetchDetailInfo(id);
  }

  componentDidUpdate(prevProps: any) {
    const {
      location: { query: { id } },
    } = this.props;
    if (id && prevProps.location.query.id !== id) {
      this.fetchDetailInfo(id);
    }
  }

  componentWillUnmount() {
    this.fetchAction('clearInfo');
  }

  fetchDetailInfo = (id: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'propertyCompanySaveAndEdit/fetch',
      payload: { id, loadUser: 1 },
    });
  };

  mergeValues = (name: string, value: number | string | object) => {
    const { formValues } = this.state;
    formValues[name] = value;
    this.setState({ formValues });
  };

  handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;

      const validation = /^[0-9 -]*$/;
      if (!validation.test(values.telephone)) {
        message.error('请正确输入固定电话!');
      } else {
        const { location: { query } } = this.props;
        const params = { ...values };
        if (query && query.id) params.id = query.id;
        this.fetchAction('saveOrUpdate', params);
      }
    });
  };

  fetchAction = (typeName: string, payload = {}) => {
    const { dispatch } = this.props;
    dispatch({
      type: `propertyCompanySaveAndEdit/${typeName}`,
      payload,
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
      detailInfo,
    } = this.props;

    return (
      <Fragment>
        <PageHeader />

        <Form hideRequiredMark className="tableListForm" onSubmit={this.handleSubmit}>
          <Card title="基本信息" bordered={false}>
            <Row gutter={12}>
              <Col md={8} sm={24}>
                <Item label="物业公司" colon={false}>
                  {getFieldDecorator('name', {
                    initialValue: detailInfo.name,
                    rules: [{ required: true, message: '请输入物业公司' }],
                  })(
                    <Input allowClear placeholder="请输入" autoComplete="off" />,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={12}>
              <Col md={8} sm={24}>
                <Item label="固定电话" colon={false}>
                  {getFieldDecorator('telephone', {
                    initialValue: detailInfo.telephone,
                    rules: [{ required: true, message: '请输入固定电话' }],
                  })(
                    <Input allowClear placeholder="请输入" autoComplete="off" />,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={12}>
              <Col md={8} sm={24}>
                <Item label="公司地址" colon={false} className="marginB0Import">
                  {getFieldDecorator('address', {
                    initialValue: detailInfo.address,
                    rules: [{ required: true, message: '请输入快递公司' }],
                  })(
                    <TextArea placeholder="请输入" autoComplete="off" />,
                  )}
                </Item>
              </Col>
            </Row>
          </Card>

          <Card title={detailInfo.createUser && '日志信息'} bordered={false}>
            {detailInfo.createUser && (
              <Timeline>
                <Timeline.Item>最近操作人：{detailInfo.updateUserName}</Timeline.Item>
                <Timeline.Item>最近操作时间：{detailInfo.updateTime}</Timeline.Item>
                <Timeline.Item>创建人：{detailInfo.createUserName}</Timeline.Item>
                <Timeline.Item>创建时间：{detailInfo.createTime}</Timeline.Item>
              </Timeline>
            )}
            <div>
              <Button
                type="primary"
                htmlType="submit"
              >
                保存
              </Button>
              <Button
                ghost
                type="primary"
                className="marginL16"
                onClick={() => router.goBack()}
              >
                取消
              </Button>
            </div>
          </Card>
        </Form>
      </Fragment>
    );
  }
}

export default Form.create<saveAndEditProps>()(saveAndEditInfo);
